package com.framework.boc.admin.security.service;

import com.framework.boc.admin.security.sms.exception.SmsCodeException;
import com.framework.boc.admin.sms.SmsCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    HttpServletRequest httpServletRequest;

    @Override
    public UserDetails loadUserByUsername(String phoneNum) throws UsernameNotFoundException {
        SmsCode smsCode = (SmsCode) httpServletRequest.getSession().getAttribute(phoneNum);

        if (smsCode == null) {
            throw new UsernameNotFoundException("短信验证码不存在");
        }

        if (smsCode.isExpire()) {
            throw new UsernameNotFoundException("短信验证码已过期");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("admin"));

        return new User(phoneNum, smsCode.getCode(), authorities);
    }
}
